'''
This file is part of DopplerShift.

    DopplerShift is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    DopplerShift is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with DopplerShift.  If not, see <http://www.gnu.org/licenses/>.
'''

import zipfile
import StringIO

class InMemoryZip(object):
    compression = zipfile.ZIP_DEFLATED
    def __init__(self, data=''):
        '''
        Creating in memory zip file
        '''
        self._zipdata = StringIO.StringIO(data)
        
    def append(self, filename_in_zip, file_content):
        '''
        append file with filename_in_zip and content as file_contnet to zip file 
        '''
        zh = self._getZipHandler('a')
        zh.writestr(filename_in_zip, file_content)
        
        for zfile in zh.filelist:
            zfile.create_system = 0
        return self
    def read(self):
        '''
        return a string with file contents of the in memory zip
        '''
        self._zipdata.seek(0)
        return self._zipdata.read()
    def _getZipHandler(self, mode='r'):
        return zipfile.ZipFile(self._zipdata, mode, self.compression, False) 
    def namelist(self):
        return self._getZipHandler().namelist()
    def fetch(self, name, pwd=None):
        return self._getZipHandler('r').read(name, pwd)
    def testzip(self):
        return self._getZipHandler('r').testzip()
    def writetofile(self, filename):
        '''
        write inmemory zipcontent to file
        '''
        f = file(filename, 'w')
        f.write(self.read())
        f.close()

